package cn.ac.big.bigd.bigsearch;

import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by wangfan on 2017/12/26.
 */

public class ESFactory {

    private static final String ES_CLUSTER_NAME = "bigd";
    private static final String ES_HOST = "192.168.118.74";
    private static final int ES_PORT = 9300;
    public static final String INDEX = "bigsearch";


    public synchronized static TransportClient getClient() {
        Settings esSettings = Settings.builder()
                .put("cluster.name", ES_CLUSTER_NAME) //设置ES实例的名称
                .put("client.transport.sniff", true) //自动嗅探整个集群的状态，把集群中其他ES节点的ip添加到本地的客户端列表中
                .build();
        try {
            return new PreBuiltTransportClient(esSettings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(ES_HOST), ES_PORT));
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        TransportClient client = ESFactory.getClient();
        GetResponse response = client.prepareGet(INDEX, "bioproject_entry", "PRJCA000396")
                .execute().actionGet();
        System.out.println("response.getId():" + response.getId());
        System.out.println("response.getSourceAsString():" + response.getSourceAsString());



    }
}
